const robot = require('robotjs');
const { exec } = require('child_process');

class InactivityMonitor {
  constructor(inactivityTime = 60000) { // 默认1分钟
    this.inactivityTime = inactivityTime;
    this.lastActivityTime = Date.now();
    this.timer = null;
    this.isRunning = false;
    this.screenSize = robot.getScreenSize();

    console.log('屏幕尺寸:', this.screenSize);
    console.log(`监控已启动，${inactivityTime/1000}秒无操作后执行动作`);
  }

  // 开始监控
  start() {
    if (this.isRunning) return;

    this.isRunning = true;
    this.lastActivityTime = Date.now();
    this.startMonitoring();
    this.setupActivityListeners();

    console.log('无操作监控已启动...');
  }

  // 停止监控
  stop() {
    this.isRunning = false;
    if (this.timer) {
      clearTimeout(this.timer);
      this.timer = null;
    }
    console.log('监控已停止');
  }

  // 开始监控超时
  startMonitoring() {
    if (!this.isRunning) return;

    const now = Date.now();
    const idleTime = now - this.lastActivityTime;

    if (idleTime >= this.inactivityTime) {
      console.log(`检测到 ${idleTime/1000} 秒无操作，执行防休眠动作`);
      this.performAntiSleepAction();
      this.lastActivityTime = now; // 重置活动时间
    }

    // 每5秒检查一次
    this.timer = setTimeout(() => this.startMonitoring(), 5000);
  }

  // 记录用户活动
  recordActivity() {
    if (!this.isRunning) return;

    this.lastActivityTime = Date.now();
    console.log(`检测到用户活动，重置计时器 (${new Date().toLocaleTimeString()})`);
  }

  // 设置活动监听（模拟监听，因为robotjs没有事件监听）
  setupActivityListeners() {
    // 由于robotjs没有事件监听，我们使用轮询方式检测鼠标移动
    this.setupMousePolling();
    this.setupKeyboardPolling();
  }

  // 轮询检测鼠标移动
  setupMousePolling() {
    let lastMousePos = robot.getMousePos();

    setInterval(() => {
      if (!this.isRunning) return;

      const currentPos = robot.getMousePos();
      if (currentPos.x !== lastMousePos.x || currentPos.y !== lastMousePos.y) {
        this.recordActivity();
        lastMousePos = currentPos;
      }
    }, 1000); // 每秒检查一次
  }

  // 检测键盘活动（通过检查修饰键状态）
  setupKeyboardPolling() {
    let lastKeyState = this.getKeyState();

    setInterval(() => {
      if (!this.isRunning) return;

      const currentKeyState = this.getKeyState();
      if (JSON.stringify(currentKeyState) !== JSON.stringify(lastKeyState)) {
        this.recordActivity();
        lastKeyState = currentKeyState;
      }
    }, 1000);
  }

  // 获取特殊键状态
  getKeyState() {
    return {
      shift: robot.keyToggle('shift', 'down') ? 'down' : 'up',
      control: robot.keyToggle('control', 'down') ? 'down' : 'up',
      alt: robot.keyToggle('alt', 'down') ? 'down' : 'up',
      command: robot.keyToggle('command', 'down') ? 'down' : 'up'
    };
  }

  // 执行防休眠动作
  performAntiSleepAction() {
    try {
      console.log('执行防休眠动作...');

      // 1. 获取当前鼠标位置
      const originalPos = robot.getMousePos();
      console.log('原始位置:', originalPos);

      // 2. 移动到中间随机位置（避免一直在同一个点点击）
      // 计算中间位置
      const centerX = this.screenSize.width / 2;
      const centerY = this.screenSize.height / 2;
      // 随机移动到中间位置
      const targetX = Math.max(100, Math.min(this.screenSize.width - 100,
        centerX + (Math.random() > 0.5 ? 50 : -50)));
      const targetY = Math.max(100, Math.min(this.screenSize.height - 100,
        centerY + (Math.random() > 0.5 ? 50 : -50)));

      // 3. 平滑移动鼠标
      this.smoothMove(originalPos.x, originalPos.y, targetX, targetY, 500);

      // 4. 轻微点击（右键，避免误操作）
      setTimeout(() => {
        // robot.mouseClick('right');
        // console.log('执行右键点击');

        // 5. 移回原位置
        setTimeout(() => {
          this.smoothMove(targetX, targetY, originalPos.x, originalPos.y, 500);
          console.log('返回原始位置');
        }, 200);

      }, 600);

    } catch (error) {
      console.error('执行防休眠动作失败:', error);
    }
  }

  // 平滑移动鼠标
  smoothMove(fromX, fromY, toX, toY, duration = 1000) {
    const steps = 20;
    const stepDelay = duration / steps;

    for (let i = 0; i <= steps; i++) {
      setTimeout(() => {
        const progress = i / steps;
        const easeProgress = this.easeInOutCubic(progress);

        const currentX = fromX + (toX - fromX) * easeProgress;
        const currentY = fromY + (toY - fromY) * easeProgress;

        robot.moveMouse(Math.round(currentX), Math.round(currentY));
      }, i * stepDelay);
    }
  }

  // 缓动函数（使移动更自然）
  easeInOutCubic(t) {
    return t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2;
  }

  // 获取状态信息
  getStatus() {
    const idleTime = Date.now() - this.lastActivityTime;
    return {
      isRunning: this.isRunning,
      idleTime: Math.round(idleTime / 1000),
      inactivityThreshold: this.inactivityTime / 1000,
      willTriggerIn: Math.max(0, Math.round((this.inactivityTime - idleTime) / 1000))
    };
  }
}

// 使用示例
const monitor = new InactivityMonitor(60 * 1000); // 1分钟无操作

// 启动监控
monitor.start();

// 状态显示
setInterval(() => {
  const status = monitor.getStatus();
  console.log(`状态: ${status.isRunning ? '运行中' : '已停止'} | 无操作时间: ${status.idleTime}秒 | ${status.willTriggerIn > 0 ? `${status.willTriggerIn}秒后触发` : '即将触发'}`);
}, 10000);

// 优雅退出
process.on('SIGINT', () => {
  console.log('\n正在停止监控...');
  monitor.stop();
  process.exit(0);
});
// 每天下午七点51自动退出程序
setInterval(() => {
  // 如果时间到了 19:52 退出程序
  const now = new Date();
  if (now.getHours() === 19 && now.getMinutes() === 10) {
    console.log('时间到了 19:10 退出程序');
    monitor.stop();
    process.exit(0);
  }
}, 1000);


// 测试手动重置
console.log(`
使用方法:
- 程序会自动监控鼠标键盘活动
- 1分钟无操作后会自动移动鼠标并点击
- 按 Ctrl+C 退出程序
- 移动鼠标或按键盘会重置计时器
`);
